package edu.mapi.ir.viewer;

import java.awt.BorderLayout;
import java.awt.Container;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Vector;

import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.UIManager;

import edu.mapi.ir.gui.GuiUtils;
import edu.mapi.ir.log.LogReplay;
import edu.mapi.ir.log.ReplayPanel;

/**
 * @author ZP
 */
public class ReplayApplet extends JApplet {

	private static MazePanel mazePanel;
	private static ScoreWall scoreWall;
	private static ReplayPanel replayPanel;
	private static Maze maze = null;
	private static LogReplay replay;
	
	private static Vector<GridPosition> grid = null;	
	
	public static void init(Container container) {
		mazePanel = new MazePanel();
		scoreWall = new ScoreWall();
		replayPanel = new ReplayPanel(replay, mazePanel, scoreWall);
		
		try {
			grid = GridPosition.readString(replay.getGridXML());						
			maze = Maze.readString(replay.getLabXML());
			maze.setGrid(grid);
			mazePanel.setMaze(maze);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		container.setLayout(new BorderLayout());		
		
		container.add(scoreWall, BorderLayout.NORTH);
		container.add(mazePanel, BorderLayout.CENTER);
		container.add(replayPanel, BorderLayout.SOUTH);
	}
	
	public void init() {
		
		replay = LogReplay.parseLog(ReplayApplet.class.getClassLoader().getResourceAsStream("replay.log"));	
		super.init();
		init(this);
	}
	
	@Override
	public void stop() {
		super.stop();
		replayPanel.stop.actionPerformed(null);
	}
	
	@Override
	public void start() {
		super.start();
		replayPanel.play.actionPerformed(null);
	}
	
	public static void main(String[] args) {
		if (args.length >= 1 && new File(args[0]).canRead()) {
			replay = LogReplay.parseLog(new File(args[0]).getAbsolutePath());
		}
		
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());			
		}
		catch(Exception e){
		}
		
		replay = LogReplay.parseLog(ReplayApplet.class.getClassLoader().getResourceAsStream("replay.log"));
		JFrame mainFrame = new JFrame("MazeReplay");
		
		init(mainFrame);
		
		mainFrame.setIconImage(GuiUtils.getImage("imgs/r2d2.png"));
		mainFrame.setSize(745, 550);
		GuiUtils.centerOnScreen(mainFrame);
		
		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainFrame.setVisible(true);
	}
}
